<?php
/*
 * File: LoginController.php
 * Project: NewDemo
 * Created Time: 2024-05-30 09:52:25 am
 * Author: WangYuQiang && WangpeiGang (719404171@qq.com)
 * -----
 * Last Modified: 2024-12-04 4:01:14 pm
 * Modified By: WangYuQiang (719404171@qq.com>)
 * -----
 * Copyright (c) 2023 - 2024 成都睿創科技有限公司
 */



namespace App\Http\Controllers\Api;

use App\Models\User;
use Illuminate\Http\Request;
use Tests\CreatesApplication;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Api\BaseController;

class LoginController extends Controller{

    private $Users;
    public function __construct()
    {
        $this->Users = new User();
    }

    /**
     * @param Request $request
     * @return array
     * 用戶登錄
     */
    public function login(Request $request){
        if (!$request->has("user_phone")) {
            return $this->error(__('api.phone_missing'));
        } else if (!$request->has("user_password")) {
            return $this->error(__('api.password_missing'));
        } else {
            // 传递给attempt的数组只是一个数组；它与您的数据库表无关。您不必使用'user_phone'和'user_password'。
            if (Auth::attempt(['user_phone' => request('user_phone'), 'password' =>request('user_password') ,'area_code' => request('area_code'),'user_status' => 1])) {
                $user = Auth::user();
                $token = $user->createToken($user['user_id'])->accessToken;
                //修改登錄信息
                $addInfo = User::where('user_id', $user['user_id'])
                               ->update([ 'token_type' => $request->post('token_type'), 
                                          'client_id' => $request->post('client_id'),
                                          'login_type' => 1,
                                          'finally_at' => date('Y-m-d H:i:s') ]);
                if ($addInfo) {
                    //登錄次數加一
                    User::where('user_id', $user['user_id'])->increment('login_time');
                    $results['token'] = $token;
                    $results['user_email'] = $user['user_email'];
                    $results['user_name'] = $user['user_name'];
                    $results['user_phone'] = $user['user_phone'];
                    $results['user_id'] = $user['user_id'];
                    $results['area_code'] = $user['area_code'];
                    return $this->success(__('api.login_success') , $results);  
                } else {
                    return $this->error(__('api.login_error'));
                }
            } else {
                return $this->error(__('api.login_error'));
            }
        }
    }







/**********************************************************END**********************************************************************/
}
